package com.fire.user.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fire.user.constants.BusinessConstants;
import com.fire.user.service.ITMitClientService;
import com.fire.user.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fire.core.util.Public;
import com.fire.core.util.ToolUtil;
import com.fire.user.dao.UsersMapper;
import com.fire.user.model.TMitClient;
import com.fire.user.model.TMitClientRelation;
import com.fire.user.model.User;
import com.fire.user.service.IClientService;
import com.fire.user.service.ITMitClientRelationService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * 客户 服务实现类
 * @author raoyuxing
 *
 */
@Service
public class ClientServiceImpl implements IClientService {
	private static final Logger LOGGER = LoggerFactory.getLogger(ClientServiceImpl.class);

	@Autowired
	private ITMitClientService clientService;
	
	@Autowired
	private ITMitClientRelationService clientRelationService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private UsersMapper usersMapper;

	
	/**
	 * 增加客户信息
	 * @author raoyuxing
	 * @param map
	 * @return
	 */
	@Override
	@Transactional(rollbackFor=Exception.class)
	public Map addClientInfo(Map map) {
    	LOGGER.debug("ClientServiceImpl.addClientInfo获取到的map消息" + map);

		//更新或保存投保人信息并返回客户ID
		Map application = (Map) map.get("application");
		if("4".equals(map.get("sourcetype").toString())) {
			application.put("sourcetype", "2");
		}
		String sclientid = clientInfo(application);
    	
    	//更新或保存被保人信息并返回客户ID
		Map insuredclient = (Map) map.get("insuredclient");
		if("4".equals(map.get("sourcetype").toString())) {
			insuredclient.put("sourcetype", "3");
		}
		String tclientid = clientInfo(insuredclient);
		
		//保存投保人与被保人的关系信息
		TMitClientRelation clientRelation = new TMitClientRelation();
		clientRelation.setSclientid(Integer.valueOf(sclientid));
		clientRelation.setTclientid(Integer.valueOf(tclientid));
		clientRelation.setCreatetime(new Date());
		clientRelation.setUpdatetime(new Date());
		Integer relation = Integer.valueOf(String.valueOf(map.get("relationsship")));
		clientRelation.setRelation(relation);
		if (relation == BusinessConstants.CLIENT_RELATION_ONESELF) {
			clientRelation.setRelationname("本人");
		}else if(relation == BusinessConstants.CLIENT_RELATION_PARTNER){
			clientRelation.setRelationname("配偶");
		}else if(relation == BusinessConstants.CLIENT_RELATION_PARENTS){
			clientRelation.setRelationname("父母");
		}else if(relation == BusinessConstants.CLIENT_RELATION_CHILDREN){
			clientRelation.setRelationname("子女");
		}else if(relation == BusinessConstants.CLIENT_RELATION_BROTHERSORSISTERS){
			clientRelation.setRelationname("兄弟姐妹");
		}else if(relation == BusinessConstants.CLIENT_RELATION_GRANDPARENTS){
			clientRelation.setRelationname("祖父母、外祖父母");
		}else if(relation == BusinessConstants.CLIENT_RELATION_GRANDCHILDREN){
			clientRelation.setRelationname("祖孙、外祖孙");
		}else if(relation == BusinessConstants.CLIENT_RELATION_EMPLOYEE){
			clientRelation.setRelationname("雇佣");
		}else if(relation == BusinessConstants.CLIENT_RELATION_OTHER){
			clientRelation.setRelationname("其他");
		}
		clientRelationService.insert(clientRelation);
		
		Map result = new HashMap<>(3);
		
		result.put("sclientid", sclientid);
		result.put("tclientid", tclientid);
		result.put("relationsship", relation);
		
		return result;
		
	}
	
	/**
	 * 更新或保存客户信息并返回客户ID
	 * @author raoyuxing
	 * @return
	 */
	@Transactional(rollbackFor=Exception.class)
	public String clientInfo(Map clientinfo){

    	LOGGER.debug("ClientServiceImpl.addClientInfo更新或保存被保人信息并返回客户ID" + clientinfo);
		// 从投保人或者被保人中提取客户信息组成客户对象
		TMitClient client = Public.toBean(TMitClient.class, clientinfo);
		String clientName = "";
		String applicationname = "applicationname";
		String insuredname = "insuredname";
		if (ToolUtil.isNotEmpty(clientinfo.get(applicationname))) {
			clientName = String.valueOf(clientinfo.get(applicationname));
		}else if (ToolUtil.isNotEmpty(clientinfo.get(insuredname))){
			clientName = String.valueOf(clientinfo.get(insuredname));
		}
		String idvaliditydate = "";
		String idtalidity1 = "idtaliditydate";
		String idtalidity2 = "idvaliditydate";
		if (ToolUtil.isNotEmpty(clientinfo.get(idtalidity1))) {
			idvaliditydate = String.valueOf(clientinfo.get(idtalidity1));
		}else if (ToolUtil.isNotEmpty(clientinfo.get(idtalidity2))){
			idvaliditydate = String.valueOf(clientinfo.get(idtalidity2));
		}
		client.setClientName(clientName);
		if (ToolUtil.isNotEmpty(clientinfo.get("phone"))) {
			client.setMobilePhone(String.valueOf(clientinfo.get("phone")));
		}
		if (ToolUtil.isNotEmpty(clientinfo.get("sourcetype"))) {
			client.setSourcetype(String.valueOf(clientinfo.get("sourcetype")));
		}
		if (ToolUtil.isNotEmpty(clientinfo.get("idtype"))) {
			client.setIdType(Integer.valueOf(String.valueOf(clientinfo.get("idtype"))));
		}
		client.setIdValidityDate(idvaliditydate);
		if (ToolUtil.isNotEmpty(clientinfo.get("idno"))) {
			client.setIdno(String.valueOf(clientinfo.get("idno")));
		}
		if (ToolUtil.isNotEmpty(clientinfo.get("email"))) {
			client.setClientEmail(String.valueOf(clientinfo.get("email")));
		}
		if (ToolUtil.isNotEmpty(clientinfo.get("isssn"))) {
			client.setIsssn(Integer.valueOf(String.valueOf(clientinfo.get("isssn"))));
		}
		
		//更新或保存客户信息并返回客户ID
		EntityWrapper<TMitClient> clientWrapper = new EntityWrapper<>();
		String idno = client.getIdno();
		clientWrapper.eq("idno", idno);
		String clientId = "";
		List<TMitClient> clients = clientService.selectList(clientWrapper);
		if (ToolUtil.isNotEmpty(clients)) {
			//更新客户信息并返回客户ID
			client.setUpdatetime(new Date());
			String userId = userInfo(client);
			clientService.update(client, clientWrapper);
			clientId = String.valueOf(clients.get(0).getClientid());
		}else{
			synchronized (this){
				if (ToolUtil.isNotEmpty(clients)) {
					//更新客户信息并返回客户ID
					client.setUpdatetime(new Date());
					String userId = userInfo(client);
					clientService.update(client, clientWrapper);
					clientId = String.valueOf(clients.get(0).getClientid());
				}else{
					//保存客户信息并返回客户ID
					String userId = userInfo(client);
					client.setUserid(userId);
					clientService.insertClient(client);
					clientId = String.valueOf(client.getClientid());
				}
			}
		}
		return clientId;
	}
	
	/**
	 * 用户不存在则添加用户
	 * @author raoyuxing
	 * @return
	 */
	@Transactional(rollbackFor=Exception.class)
	public String userInfo(TMitClient client){
    	LOGGER.info("ClientServiceImpl.clientInfo用户不存在则添加用户并返回用户ID:" + client);
		String userId = "";
		String phone = client.getMobilePhone();
		User users = usersMapper.selectByPhone(phone);
		if (null!=users) {
			userId = String.valueOf(users.getUserid());
		}else{
			User user = new User();
			user.setAliasname(client.getClientName());
			user.setResourceid(client.getSourcetype());
			user.setPhone(phone);
			user.setChannelid(1);
			user.setChannelname("移保通");
			userService.insertUser(user);
			userId = String.valueOf(user.getUserid());
		}
		return userId;
	}

}
